#include "stm32f10x.h"
#include "mcp4451.h"
#include "i2c.h"
#include <math.h>
#define DIGIPOT_I2C_FACTOR 106.7
#define DIGIPOT_I2C_MAX_CURRENT 2.5


static uint8_t current_to_wiper(float current)
{
    return (uint8_t)(ceil((float)((DIGIPOT_I2C_FACTOR * current))));
}

// This is for the MCP4451 I2C based digipot
void Set_Current(int channel, float current)
{
    current = min((float)max(current, 0.0f), DIGIPOT_I2C_MAX_CURRENT);
    // these addresses are specific to Azteeg X3 Pro, can be set to others,
    // In this case first digipot is at address A0=0, A1= 0, second one is at A0=0, A1= 1
    uint8_t addr = 0x2C; // channel 0-3
    if (channel >= 4)
    {
        addr = 0x2E; // channel 4-7
        channel -= 4;
    }

    // Initial setup
    Single_Write(addr, 0x40, 0xff);
    Single_Write(addr, 0xA0, 0xff);

    // Set actual wiper value
    uint8_t addresses[4] = { 0x00, 0x10, 0x60, 0x70 };
    Single_Write(addr, addresses[channel], current_to_wiper(current));
}

